import asyncio
from time import sleep
from pymodbus.client import ModbusSerialClient
from pymodbus.exceptions import ModbusException

# 配置串口参数
SERIAL_PORT = "COM2"  # Windows系统下的串口设备，Linux系统可能是/dev/ttyUSB0等
BAUDRATE = 9600
UNIT_ID = 1  # Modbus从站的设备地址

async def run_client():
    client = ModbusSerialClient(
        port=SERIAL_PORT,
        baudrate=BAUDRATE,
        timeout=1
    )

    try:
        # 连接到从站
        if client.connect():
            print("Connected to Modbus RTU server")

            while(True):
                sleep(1)
                # 读取保持寄存器
                address = 0  # 寄存器地址
                count = 8    # 读取数量
                try:
                    # 从地址 0 开始读取 10 个离散输入寄存器
                    response = client.read_discrete_inputs(address=address, count=count, slave=UNIT_ID)
                    if response.isError():
                        print(f"Error reading coil registers: {response}")
                    else:
                        print(f"离散输入状态:", response.bits)
                except ModbusException as e:
                    print("Exception while reading holding registers:", e)
                # 读取线圈寄存器
                address = 0  # 寄存器地址
                count = 8    # 读取数量
                try:
                    response = client.read_coils(address=address, count=count, slave=UNIT_ID)
                    if response.isError():
                        print(f"Error reading coil registers: {response}")
                    else:
                        print(f"线圈寄存器状态:", response.bits)
                except ModbusException as e:
                    print("Exception while reading holding registers:", e)

                # 读取保持寄存器
                address = 0  # 寄存器地址
                count = 10    # 读取数量
                try:
                    response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
                    if response.isError():
                        print(f"Error reading holding registers: {response}")
                    else:
                        print(f"保持寄存器:", response.registers)
                except ModbusException as e:
                    print("Exception while reading holding registers:", e)

                # 读取输入寄存器
                address = 0  # 寄存器地址
                count = 10    # 读取数量
                try:
                    response = client.read_input_registers(address=address, count=count, slave=UNIT_ID)
                    if response.isError():
                        print(f"Error reading holding registers: {response}")
                    else:
                        print(f"输入寄存器 :", response.registers)
                except ModbusException as e:
                    print("Exception while reading holding registers:", e)


            

            # # 写入保持寄存器
            # new_value = 0x5678  # 新的寄存器值
            # try:
            #     response = client.write_register(address=address, value=new_value, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error writing holding register: {response}")
            #     else:
            #         print(f"Holding register at address {address} set to {new_value}")
            # except ModbusException as e:
            #     print("Exception while writing holding register:", e)

            # # 再次读取保持寄存器，验证写入是否成功
            # try:
            #     response = client.read_holding_registers(address=address, count=count, slave=UNIT_ID)
            #     if response.isError():
            #         print(f"Error reading holding registers after write: {response}")
            #     else:
            #         print(f"Holding register value (address {address}) after write:", response.registers[0])
            # except ModbusException as e:
            #     print("Exception while re - reading holding registers:", e)

        else:
            print("Failed to connect to Modbus RTU server")

    except Exception as e:
        print("General error:", e)

    finally:
        # 关闭连接
        client.close()
        print("Modbus connection closed")


if __name__ == "__main__":
    asyncio.run(run_client())